package main.java.sales;

import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * SalesReducer
 *
 * @author zhangyimin
 * @version 1.0
 * @date 2018-11-07 上午9:50
 */
public class ProductsReducer extends Reducer<IntWritable, Text,Text,Text> {

    @Override
    protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
//        Double total=0.00;
//        Integer totalCount=0;
//        for (Text amount:values){
//            total+=amount.get();
//            totalCount++;
//        }

        String resKey="";
        Map<String,Double> map=new HashMap<>();



        for (Text content:values){
            JSONObject jsonObject = JSONObject.parseObject(content.toString());


            if (jsonObject.containsKey("PROD_NAME")){
                resKey=jsonObject.getString("PROD_NAME");
            }else{
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()){
                    String keyName=entry.getKey();
                    Double amount=Double.parseDouble(entry.getValue().toString());
                    Double tmp=0.0;
                    if (map.get(keyName)!=null){
                        tmp=map.get(keyName);
                        map.put(keyName,tmp+amount);
                    }else{
                        map.put(keyName,amount);
                    }
                }
//                String year=
//                map.put()
            }

        }

        context.write(new Text(resKey),new Text(JSONObject.toJSONString(map)));

    }
}
